#!/usr/bin/env python3
# -*- coding: utf-8 -*-

'使用@property'
'''
get/set设置属性的调用方法又略显复杂，没有直接用属性这么直接简单。
有没有既能检查参数，又可以用类似属性这样简单的方式来访问类的变量呢？对于追求完美的Python程序员来说，这是必须要做到的！
还记得装饰器（decorator）可以给函数动态加上功能吗？对于类的方法，装饰器一样起作用。Python内置的@property装饰器就是负责把一个方法变成属性调用的：
'''


class Stu(object):
    def __init__(self, name, age=0):
        self.name = name
        self.age = age

    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, name):
        if not isinstance(name, str):
            raise ValueError('name must be a string!')
        if len(name) < 2 or len(name) > 16:
            raise ValueError('name\'s length must between 2 and 16!')
        self.__name = name

    @property
    def age(self):
        return self.__age

    @age.setter
    def age(self, age):
        if not isinstance(age, int):
            raise ValueError('age must be an integer!')
        if age < 0 or age > 150:
            raise ValueError('age must between 0 and 150!')
        self.__age = age

    @property
    def info(self):
        return [self.name, self.age]


s1 = Stu('Lili')
# s2 = Stu('Miao',-5)
s2 = Stu('Miao', 5)
s3 = Stu('Ming', 0)
s4 = Stu('Xiao', 25)
s5 = Stu('刘凯', 30)

S = [s1, s2, s3, s4, s5]
for i in S:
    print(i.info)


class Screen():
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def width(self):
        return self.__width

    @width.setter
    def width(self, width):
        if not isinstance(width, int):
            raise ValueError('width must be an integer!')
        if width < 0:
            raise ValueError('width must not less than 0!')
        self.__width = width

    @property
    def height(self):
        return self.__height

    @height.setter
    def height(self, height):
        if not isinstance(height, int):
            raise ValueError('height must be an integer!')
        if height < 0:
            raise ValueError('height must not less than 0!')
        self.__height = height

    @property
    def resolution(self):
        return self.width * self.height

    @property
    def info(self):
        return [self.width, self.height]


s = Screen(1366, 768)
print(s.info, s.resolution)

assert s.width > s.height, 'width:%s <= height:%s' % (s.width, s.height)
# assert 用来判断语句的真假，如果为假的话将触发AssertionError错误
